package com.cloud.pole.common.util;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description: DateFormatEditor
 * @Author zoulong
 * @Time 2018年06月13日 15:24
 */

public class DateFormatEditor extends PropertyEditorSupport {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            //防止空数据出错
            if (StringUtils.isNotBlank(text)) {
                date = format.parse(text);
            }
        } catch (ParseException e) {
            format = new SimpleDateFormat("yyyy-MM-dd");
            try {
                date = format.parse(text);
            } catch (ParseException e1) {
                format = new SimpleDateFormat("yyyy-MM");
                try {
                    date = format.parse(text);
                } catch (ParseException e2) {
                    format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                    try {
                        date = format.parse(text);
                    } catch (ParseException e3) {
                        format = new SimpleDateFormat("yyyy/MM/dd");
                        try {
                            date = format.parse(text);
                        } catch (ParseException e4) {
                            format = new SimpleDateFormat("yyyy/MM");
                            try {
                                date = format.parse(text);
                            } catch (ParseException e5) {
                                format = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
                                try {
                                    date = format.parse(text);
                                } catch (ParseException e6) {
                                    format = new SimpleDateFormat("yyyyMMdd");
                                    try {
                                        date = format.parse(text);
                                    } catch (ParseException e7) {
                                        format = new SimpleDateFormat("yyyyMM");
                                        try {
                                            date = format.parse(text);
                                        } catch (Exception e8) {
                                            logger.error("自动绑定日期数据出错", e);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        setValue(date);
    }
}
